//
//  FoldersViewController.m
//  ExchangeClient
//
//  Created by Антон on 03.12.12.
//  Copyright (c) 2012 Сураева Яна. All rights reserved.
//

#import "FoldersViewController.h"
#import "SQLQueries.h"
#import "MailViewController.h"
#import "Folder.h"
#import "SendQueryToDB.h"
#import <sqlite3.h>


@interface FoldersViewController ()

@end

@implementation FoldersViewController
@synthesize requestHandlerInstance, foldersArray, table;

-(void)dealloc
{

    [foldersArray release];
    [folderID release];
    [table release];
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
      
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
 
}

- (void)viewDidLoad
{
    [self initData];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [super viewDidLoad];
    

}

- (void)didReceiveMemoryWarning
{
    self.title=@"Folders";
    [super didReceiveMemoryWarning];
}





-(void) initData{
    
    foldersArray=[NSMutableArray new];
    static sqlite3 *database = nil;
    sqlite3_stmt *selectstmt;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"FoldersForMail"];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
	NSError *error;
	BOOL success = [fileManager fileExistsAtPath:path];
	if(!success) {
		NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"FoldersForMail"];
		success = [fileManager copyItemAtPath:defaultDBPath toPath:path error:&error];
		
		if (!success)
			NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
	}
    

    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        NSString *sql = [[[NSString alloc]initWithString:@"SELECT name FROM users"]autorelease];
        if(sqlite3_prepare_v2(database, [sql cStringUsingEncoding:NSUTF8StringEncoding], -1, &selectstmt, NULL) == SQLITE_OK) {
            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
                NSString *folderObj =[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
                
                [foldersArray addObject:folderObj];
                
            }
        }
    }
    else
        sqlite3_close(database);

}




- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return [foldersArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
    }
    
    
    
    cell.textLabel.text=[foldersArray objectAtIndex:indexPath.row];
    cell.backgroundColor=[UIColor whiteColor];
    return cell;
}


-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MailViewController *view2=[[[MailViewController alloc]initWithNibName:@"MailViewController" bundle:nil]autorelease];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    static sqlite3 *database = nil;
    folderID=[NSString new];
    sqlite3_stmt *selectstmt;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory= [paths objectAtIndex:0];
    NSString *path=[documentsDirectory stringByAppendingPathComponent:@"FoldersForMail"];
    ;
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
        
        
        NSString *sql = [[[NSString alloc]initWithString:[[@"SELECT idFolfer  FROM users WHERE name =\"" stringByAppendingString:[foldersArray objectAtIndex:indexPath.row]]stringByAppendingString:@"\""]]autorelease];
        if(sqlite3_prepare_v2(database, [sql cStringUsingEncoding:NSUTF8StringEncoding], -1, &selectstmt, NULL) == SQLITE_OK) {
            while(sqlite3_step(selectstmt) == SQLITE_ROW) {
            folderID=[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
            }
        }
    }
    [requestHandlerInstance getItemsInFolderWithID:folderID];
    
    view2.folderName=folderID;

    view2.requestHandlerInstance=requestHandlerInstance;
    
    [self.navigationController pushViewController:view2 animated:YES];

    
}




- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
